<?php
/**
* SocialEngine
*
* @category   Application_Extensions
* @package    Flashgame
* @copyright 2010 YouNet
* @license    http://www.modules2buy.com/license/
* @version    $Id: IndexController.php 6898 2010 YouNet $
* @author     To Anh
*/

/**
* @category   Application_Extensions
* @package    Flashgame
* @copyright 2010 YouNet
* @license    http://www.modules2buy.com/license/
*/
class Flashgame_IndexController extends Core_Controller_Action_Standard
{
    protected $_navigation;

    public function init()
    {
        if( !$this->_helper->requireAuth()->setAuthParams('flashgame', null, 'view')->isValid()) return;
        // @todo this may not work with some of the content stuff in here, double-check
    }

    /**
    * Browsing all approved flash games
    * 
    */
    public function indexAction()
    {
        $viewer = Engine_Api::_()->user()->getViewer();
        if( !$this->_helper->requireAuth()->setAuthParams('flashgame', null, 'view')->isValid() ) return;
         $subject = Engine_Api::_()->getItem('flashgame_param', 1);   
          $subject->search = '';
          $subject->show = $this->_getParam('show');  
          $subject->category = $this->_getParam('category');  
          $subject->page = isset($_POST["page"])?$_POST["page"]:1;
          $subject->orderby = $this->_getParam('orderby');
          $subject->tag = $this->_getParam('tag');
          $subject->save();
         $obj = new Flashgame_Api_Core();
     if($obj->getVersionSE())
     {
         $this->_helper->content
           ->setNoRender()
            ->setEnabled()
            ;    
     }
     else
        $this->_helper->content->render();

    }
    public function userratingsAction()
    {
        $this->_helper->content->render();

    }

    public function rateAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(TRUE);

        if( !$this->_helper->requireUser()->isValid() ) return;

        // Get parameters

        //$request = Zend_Controller_Front::getInstance()->getRequest();
        //$rates = $request->getParam('rates', 0);
        //$game_id = $request->getParam('flashgame_id', 0);

        $game_id = (int) $this->_getParam('flashgame_id');
        $rates = (int)  $this->_getParam('rates');

        $viewer = Engine_Api::_()->user()->getViewer();

        if ($rates == 0 || $game_id == 0)
        {
            return;
        }
        // Check game exist
        $getGame = Engine_Api::_()->flashgame()->getFlashgame($game_id);
        if (count($getGame) < 1)
        {
            return;
        }
        $rateTable = Engine_Api::_()->getDbtable('rates', 'flashgame');
        $can_rate = Engine_Api::_()->flashgame()->canRate($getGame,$viewer->getIdentity());
        // Check user rated
        if (!$can_rate)
        {
            return;
        }            
        $db = $rateTable->getAdapter();
        $db->beginTransaction();
        try
        {
            $rate = $rateTable->createRow();
            $rate->poster_id = $viewer->getIdentity();
            $rate->game_id = $game_id;
            $rate->rate_number  = $rates;
            $rate->save();
            $rates = Engine_Api::_()->flashgame()->getAVGrate($game_id);
            $getGame->rates = $rates;
            $getGame->save();
            // Commit
            $db->commit();
        }

        catch( Exception $e )
        {
            $db->rollBack();
            throw $e;
        }
        return $this->_redirect("games/".$getGame->owner_id.'/'.$game_id.'#ratearea');

    }

    public function viewAction()
    {
        $viewer = Engine_Api::_()->user()->getViewer();
        $game_id = $this->_getParam('flashgame_id');
        $flashgame = Engine_Api::_()->getItem('flashgame', $game_id); 
        // check can rate
        if (!$viewer->getIdentity())
            $this->view->can_rate = $can_rate = 0;
        else
            $this->view->can_rate = $can_rate = Engine_Api::_()->flashgame()->canRate($flashgame,$viewer->getIdentity());

        // Get AVG rate of this game
        //$this->view->rates = $rates = Engine_Api::_()->flashgame()->getAVGrate($game_id);
        // Backup
        if (!$viewer->getIdentity() && $flashgame->paid)
            return $this->_forward('requireauth', 'error', 'core');

        if(/*$flashgame->level > 0 &&*/ $flashgame->paid && $viewer->getIdentity() !=  $flashgame->owner_id && $viewer->level_id > 1)
        {
            $getBePlayedGame = Engine_Api::_()->flashgame()->getBePlayedGame($viewer->getIdentity()/*,$flashgame->level*/);
            if ($getBePlayedGame < 1)
            {
                if (!Engine_Api::_()->flashgame()->checkEnablePayMent())
                {
                    return $this->_forward('success', 'utility', 'core', array(
                    'messages' => array("Sorry, current we don't support the payment feature. Please come back later. <br /> <a class='buttonlink icon_back' href='javascript:void(0);' onClick='history.go(-1);'>Go Back</a>")
                    ));    
                }
                else
                    return $this->_forward('success', 'utility', 'core', array(
                    'messages' => array("You must upgrade package to play this game. <br /> <a class='buttonlink icon_back' href='javascript:void(0);' onClick='history.go(-1);'>Go Back</a> or <a href='games/upgrade'>Upgrade Package</a>")
                    ));
            }


        }

        $getGame = Engine_Api::_()->flashgame()->getFlashgame($this->_getParam('flashgame_id'));

        if( !$this->_helper->requireAuth()->setAuthParams($flashgame, null, 'view')->isValid()) return;
        $can_view = $this->view->can_view = $this->_helper->requireAuth()->setAuthParams($flashgame, null, 'view')->checkRequire();
        $can_edit = $this->view->can_edit = $this->_helper->requireAuth()->setAuthParams($flashgame, null, 'edit')->checkRequire();
        $this->view->can_delete = $can_delete = $this->_helper->requireAuth()->setAuthParams($flashgame, null, 'delete')->checkRequire();

        /*
        $this->view->allowed_upload = ( $viewer && $viewer->getIdentity()
        && Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'flashgame', 'flashgame') );
        */

        $this->view->flashgame = $flashgame;
        if( $flashgame )
        {   

            /*   
            $archiveList = Engine_Api::_()->flashgame()->getArchiveList($flashgame->owner_id);
            */

            $this->view->owner = $owner = Engine_Api::_()->getItem('user', $flashgame->owner_id);
            $this->view->viewer = $viewer;

            $flashgame->view_count++;
            $flashgame->save();

            $this->view->flashgame = $flashgame;
            if( !empty($flashgame->file_id) ) {
                $storage_file = Engine_Api::_()->getItem('storage_file', $flashgame->file_id);
                if( $storage_file ) {
                    $this->view->game_location = $storage_file->map();
                }
            }
            // get tags
            $this->view->flashgameTags = $flashgame->tags()->getTagMaps();
            $this->view->userTags = $flashgame->tags()->getTagsByTagger($flashgame->getOwner());

            // get archive list
            //$this->view->archive_list = $this->handleArchiveList($archiveList);
            // get custom field values
            //$this->view->fieldsByAlias = Engine_Api::_()->fields()->getFieldsValuesByAlias($flashgame);
            // Load fields view helpers
            $view = $this->view;
            $view->addHelperPath(APPLICATION_PATH . '/application/modules/Fields/View/Helper', 'Fields_View_Helper');
            $this->view->fieldStructure = $fieldStructure = Engine_Api::_()->fields()->getFieldsStructurePartial($flashgame);

            // Get game file      
            if($flashgame->category_id !=0) $this->view->category = Engine_Api::_()->flashgame()->getCategory($flashgame->category_id);
            $this->view->userCategories = Engine_Api::_()->flashgame()->getUserCategories($this->view->flashgame->owner_id);
        }

    }

    // USER SPECIFIC METHODS
    public function manageAction()
    {
        if( !$this->_helper->requireUser()->isValid() ) return;
        $this->view->can_edit = $can_edit = $this->_helper->requireAuth()->setAuthParams('flashgame', null, 'edit')->checkRequire();
        $this->view->can_delete = $can_delete = $this->_helper->requireAuth()->setAuthParams('flashgame', null, 'delete')->checkRequire();
        $viewer = Engine_Api::_()->user()->getViewer();

        $this->view->can_create = $this->_helper->requireAuth()->setAuthParams('flashgame', null, 'create')->checkRequire();
        $this->view->allowed_upload = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'flashgame', 'photo');

        $this->view->navigation = $this->getNavigation();
        $this->view->form = $form = new Flashgame_Form_Search();
        $form->removeElement('show');

        // Populate form
        $this->view->categories = $categories = Engine_Api::_()->flashgame()->getCategories();
        foreach( $categories as $category )
        {
            $form->category->addMultiOption($category->category_id, $category->category_name);
        }

        // Process form
        $request = $this->getRequest()->getPost();

        // Process form
        if( $form->isValid($this->getRequest()->getPost()) ) {
            $values = $form->getValues();
        } else {
            $values = array();
        }

        //$customFieldValues = $form->getSubForm('custom')->getValues();
        $values['user_id'] = $viewer->getIdentity();

        // Get paginator
        $this->view->paginator = $paginator = Engine_Api::_()->flashgame()->getFlashgamesPaginator($values);
        $items_count = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('flashgame.page', 10);
        $paginator->setItemCountPerPage($items_count);

        $currentpage =  isset($_POST["page"])?$_POST["page"]:1;
        $this->view->paginator = $paginator->setCurrentPageNumber($currentpage);


        $view = $this->view;
        $view->addHelperPath(APPLICATION_PATH . '/application/modules/Fields/View/Helper', 'Fields_View_Helper');

        // maximum allowed flashgames
        $this->view->quota = $quota = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'flashgame', 'max');
        $this->view->current_count = $paginator->getTotalItemCount();
    }

    public function listAction()
    {
        // Preload info
        $viewer = Engine_Api::_()->user()->getViewer();
        $this->view->owner = $owner = Engine_Api::_()->getItem('user', $this->_getParam('user_id'));

        //$archiveList = Engine_Api::_()->flashgame()->getArchiveList($owner->getIdentity());

        $this->view->archive_list = $this->handleArchiveList($archiveList);

        $this->view->navigation = $this->getNavigation();

        // Make form
        $this->view->form = $form = new Flashgame_Form_Search();
        $form->removeElement('show');

        // Populate form
        $this->view->categories = $categories = Engine_Api::_()->flashgame()->getCategories();
        foreach( $categories as $category )
        {
            $form->category->addMultiOption($category->category_id, $category->category_name);
        }

        // Process form
        $form->isValid($this->getRequest()->getPost());
        $values = $form->getValues();
        $values['user_id'] = $owner->getIdentity();
        $this->view->assign($values);

        // Get paginator
        $this->view->paginator = $paginator = Engine_Api::_()->flashgame()->getFlashgamesPaginator($values);
        $paginator->setItemCountPerPage(10);
        $this->view->paginator = $paginator->setCurrentPageNumber( $values['page'] );

        $this->view->userTags = Engine_Api::_()->getDbtable('tags', 'core')->getTagsByTagger('flashgame', $owner);
        $this->view->userCategories = Engine_Api::_()->flashgame()->getUserCategories($owner->getIdentity());
    }

    public function createAction()
    {
        $viewer = Engine_Api::_()->user()->getViewer();
        if( !$this->_helper->requireUser()->isValid() ) return;
        $viewer = Engine_Api::_()->user()->getViewer();
        if( !$this->_helper->requireAuth()->setAuthParams('flashgame', null, 'create')->isValid()) return;


        $this->view->navigation = $this->getNavigation();
        $this->view->form = $form = new Flashgame_Form_Create();
        // set up data needed to check quota
        $values['user_id'] = $viewer->getIdentity();
        $paginator = Engine_Api::_()->getApi('core', 'flashgame')->getFlashgamesPaginator($values);
        $this->view->quota = $quota = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'flashgame', 'max');
        $this->view->current_count = $paginator->getTotalItemCount();


        // If not post or form not valid, return
        if( $this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost()) )
        {
            $table = Engine_Api::_()->getItemTable('flashgame');
            $db = $table->getAdapter();
            $db->beginTransaction();

            try
            {
                // Create flashgame
                $values = array_merge($form->getValues(), array(
                'owner_type' => $viewer->getType(),
                'owner_id' => $viewer->getIdentity(),
                ));
                $errorNotice = '';
                $errorCount = 0;
                if (empty($values['title']))
                {  
                    $errorCount++;
                    $errorNotice = '"Game Title"';      
                }

                if ($values['type']=='1')          
                {
                    if (empty($values['file_id']))
                    {
                        $errorCount++;
                        if ($errorNotice != '') 
                            $errorNotice .= ', ';
                        $errorNotice .= '"Game file"';   
                    }
                }
                else  if ($values['type']=='2')   
                    {
                        $values['embed_script'] = trim($values['embed_script']);
                        if (empty($values['embed_script']))
                        {
                            $errorCount++;
                            if ($errorNotice != '') 
                                $errorNotice .= ', ';
                            $errorNotice .= '"Embedded Script"';
                    }
                }
                else
                {
                    $errorCount++;
                    if ($errorNotice != '') 
                        $errorNotice .= ', ';
                    $errorNotice .= '"Game Source"';
                }
                if ($errorNotice != '' && $errorCount > 0)
                {
                    if ($errorCount > 1)
                        $errorNotice = 'Please complete: ' .$errorNotice.' - there are required.';
                    else
                        $errorNotice = 'Please complete: ' .$errorNotice.' - it is required.';
                    $form->addError(Zend_Registry::get('Zend_Translate')->_($errorNotice));
                    return;
                }
                $flashgame = $table->createRow();
                $values['body'] = htmlspecialchars($values['body']);
                $flashgame->setFromArray($values);

                $flashgame->save();
                // Set file

                $params = array(
                'flashgame_id' => $flashgame->getIdentity(),
                'user_id' => $viewer->getIdentity(),
                );
                // save game file

                if( $values['type'] == '1' ) {
                    if (empty($values['file_id']))
                    {        
                        $form->addError(Zend_Registry::get('Zend_Translate')->_('Please complete "Game file" - it is required.'));
                        return;
                    }

                    $game_id = Engine_Api::_()->getApi('core', 'flashgame')->createGame($_FILES['file_id'],$params);
                    $flashgame->file_id = $game_id;
                }


                else if( $values['type'] == '2' ) {
                        if (empty($values['embed_script']))
                        {        
                            $form->addError(Zend_Registry::get('Zend_Translate')->_('Please complete "Embed scripts" - it is required.'));
                            return;
                        }  
                        $flashgame->embed_script = $values['embed_script'];
                }

                $flashgame->type = $values['type'];
                // save photo file
                if( !empty($values['photo_id']) ) {
                    $photo_id = Engine_Api::_()->getApi('core', 'flashgame')->createPhoto($params,$_FILES['photo_id']);
                }
                $flashgame->photo_id = $photo_id;

                $flashgame->closed = 0;
                $flashgame->save();
                // Add tags
                $tags = preg_split('/[,]+/', $values['tags']);
                $tags = array_filter(array_map("trim", $tags));
                $flashgame->tags()->addTagMaps($viewer, $tags);

                // CREATE AUTH STUFF HERE
                $auth = Engine_Api::_()->authorization()->context;
                $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'everyone');

                if($values['auth_view']) $auth_view =$values['auth_view'];
                else $auth_view = "everyone";
                $viewMax = array_search($auth_view, $roles);

                foreach( $roles as $i=>$role )
                {
                    $auth->setAllowed($flashgame, $role, 'view', ($i <= $viewMax));
                }

                $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'everyone');
                if($values['auth_comment']) $auth_comment =$values['auth_comment'];
                else $auth_comment = "everyone";
                $commentMax = array_search($values['auth_comment'], $roles);

                foreach ($roles as $i=>$role)
                {
                    $auth->setAllowed($flashgame, $role, 'comment', ($i <= $commentMax));
                }      

                $action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer, $flashgame, 'flashgame_new');
                if($action!=null){
                    Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $flashgame);
                } 
                // Commit
                $db->commit();
                // Redirect
                return $this->_redirect("games/manage"); 
                //$allowed_upload = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'flashgame', 'photo');
                /*
                if($allowed_upload){
                return $this->_helper->redirector->gotoRoute(array('flashgame_id'=>$flashgame->flashgame_id), 'flashgame_success', true);
                }
                else return $this->_redirect("games/manage");
                */
            }

            catch( Exception $e )
            {
                $db->rollBack();
                throw $e;
            }
        }
    }

    public function editAction()
    {
        if( !$this->_helper->requireUser()->isValid() ) return;

        $viewer = Engine_Api::_()->user()->getViewer();
        $this->view->flashgame = $flashgame = Engine_Api::_()->getItem('flashgame', $this->_getParam('flashgame_id'));
        //if ($this->_helper->requireAuth()->setAuthParams('flashgame', null, 'edit')->checkRequire())

        if( !Engine_Api::_()->core()->hasSubject('flashgame') )
        {
            Engine_Api::_()->core()->setSubject($flashgame);
        }

        if( !$this->_helper->requireSubject()->isValid() ) return;
        if ($viewer->level_id > 2)
            // Backup
            if( $viewer->getIdentity() != $flashgame->owner_id || !$this->_helper->requireAuth()->setAuthParams($flashgame, null, 'edit')->isValid() )
            {
                return $this->_forward('requireauth', 'error', 'core');
            }
            // Get navigation
            $navigation = $this->getNavigation(true);
        $this->view->navigation = $navigation;
        $this->view->form = $form = new Flashgame_Form_Edit(array(
        'item' => $flashgame
        ));
        // Save flashgame entry
        $saved = $this->_getParam('saved');
        if( !$this->getRequest()->isPost() || $saved )
        {
            if( $saved )
            {
                $url = $this->_helper->url->url(array('user_id' => $viewer->getIdentity(), 'flashgame_id' => $flashgame->getIdentity()), 'flashgame_entry_view');
                $savedChangesNotice = Zend_Registry::get('Zend_Translate')->_("Your changes were saved. Click %s to view your games.",'<a href="'.$url.'">here</a>');
                $form->addNotice($savedChangesNotice);
            }

            // prepare tags
            $flashgameTags = $flashgame->tags()->getTagMaps();
            //$form->getSubForm('custom')->saveValues();

            $tagString = '';
            foreach( $flashgameTags as $tagmap )
            {
                if( $tagString !== '' ) $tagString .= ', ';
                $tagString .= $tagmap->getTag()->getTitle();
            }

            $this->view->tagNamePrepared = $tagString;
            $form->tags->setValue($tagString);
            $flashgame->body = html_entity_decode($flashgame->body, ENT_NOQUOTES);
            $form->body->setValue($flashgame->body);
            // etc
            $form->populate($flashgame->toArray());
            $auth = Engine_Api::_()->authorization()->context;
            $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'everyone');
            foreach( $roles as $role )
            {
                if( 1 === $auth->isAllowed($flashgame, $role, 'view') )
                {
                    $form->auth_view->setValue($role);
                }
                if( 1 === $auth->isAllowed($flashgame, $role, 'comment') )
                {
                    $form->auth_comment->setValue($role);
                }
            }
            return;
        }
        if( !$form->isValid($this->getRequest()->getPost()) )
        {

        }
        else
        {
            // handle save for tags
            $values = $form->getValues();


            $values['body'] = htmlspecialchars($values['body']);   
            $tags = preg_split('/[,]+/', $values['tags']);
            $tags = array_filter(array_map("trim", $tags));

            $db = Engine_Db_Table::getDefaultAdapter();
            $db->beginTransaction();
            try
            {
                //$flashgame->setFromArray($values);
                if (empty($values['title']))
                {        
                    $form->addError(Zend_Registry::get('Zend_Translate')->_('Please complete "Game Title" - it is required and special characters are not allowed.'));
                    return;
                }
                $flashgame->title = $values["title"];
                $flashgame->category_id = $values["category_id"];
                $flashgame->body = $values["body"];
                $flashgame->width = $values["width"];
                $flashgame->height = $values["height"];
                $flashgame->modified_date = date('Y-m-d H:i:s');

                $flashgame->tags()->setTagMaps($viewer, $tags);
                $params = array(
                'flashgame_id' => $flashgame->getIdentity(),
                'user_id' => $viewer->getIdentity(),
                );
                // save game file
                if( $values['type'] == '1' ) {
                    if ($values['type'] != $flashgame->type && empty($values['file_id']))
                    {
                        $form->addError(Zend_Registry::get('Zend_Translate')->_('Please complete: "Game file" - it is required.'));
                        return;
                    }    
                    if (!empty($values['file_id']))
                    {        
                        $game_id = Engine_Api::_()->getApi('core', 'flashgame')->createGame($_FILES['file_id'],$params);
                        $flashgame->file_id = $game_id;
                    }          
                }

                else if( $values['type'] == '2' ) {
                        $Trimembed_script = trim($values['embed_script']);
                        if (($values['type'] != $flashgame->type && empty($values['embed_script'])) ||  (!empty($values['embed_script']) && empty($Trimembed_script)))
                        {
                            $form->addError(Zend_Registry::get('Zend_Translate')->_('Please complete: "Embed scripts" - it is required.'));
                            return;
                        }

                        if (!empty($Trimembed_script))
                    {        
                        $flashgame->embed_script = $values['embed_script'];
                    }  

                }
                else
                {
                    $form->addError(Zend_Registry::get('Zend_Translate')->_('Please complete: "Game source" - it is required.'));
                    return;
                }
                $flashgame->type = $values['type'];

                // save photo file
                if( !empty($values['photo_id'])) {
                    $photo_id = Engine_Api::_()->getApi('core', 'flashgame')->createPhoto($params,$_FILES['photo_id']);
                    $flashgame->photo_id = $photo_id;
                }

                $flashgame->save();

                // Save custom fields
                /*
                $customfieldform = $form->getSubForm('customField');
                $customfieldform->setItem($flashgame);
                $customfieldform->saveValues();
                */

                // CREATE AUTH STUFF HERE
                $auth = Engine_Api::_()->authorization()->context;
                $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'everyone');
                if($values['auth_view']) $auth_view =$values['auth_view'];
                else $auth_view = "everyone";
                $viewMax = array_search($auth_view, $roles);
                foreach( $roles as $i=>$role )
                {
                    $auth->setAllowed($flashgame, $role, 'view', ($i <= $viewMax));
                }

                $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'everyone');
                if($values['auth_comment']) $auth_comment =$values['auth_comment'];
                else $auth_comment = "everyone";
                $commentMax = array_search($auth_comment, $roles);

                foreach ($roles as $i=>$role)
                {
                    $auth->setAllowed($flashgame, $role, 'comment', ($i <= $commentMax));
                }
                // Rebuild privacy
                $actionTable = Engine_Api::_()->getDbtable('actions', 'activity');
                foreach( $actionTable->getActionsByObject($flashgame) as $action ) {
                    $actionTable->resetActivityBindings($action);
                }
                $db->commit();
                if ($viewer->level_id < 2 && $viewer->getIdentity() != $flashgame->owner_id)
                    return $this->_redirect("admin/flashgame/manage");
                else
                    return $this->_redirect("games/manage");
            }
            catch( Exception $e )
            {
                $db->rollBack();
                throw $e;
            }
        }
    }

    public function deleteAction()
    {
        if( !$this->_helper->requireUser()->isValid() ) return;

        $this->view->navigation = $this->getNavigation();

        $viewer = Engine_Api::_()->user()->getViewer();
        $this->view->flashgame = $flashgame = Engine_Api::_()->getItem('flashgame', $this->_getParam('flashgame_id'));

        if( !$this->_helper->requireAuth()->setAuthParams($flashgame, null, 'delete')->isValid())
        {
            return $this->_forward('requireauth', 'error', 'core');
        }

        if( $this->getRequest()->isPost() && $this->getRequest()->getPost('confirm') == true )
        {
            $this->view->flashgame->delete();
            return $this->_redirect("games/manage");
        }
    }

    public function closeAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(TRUE);
        if( !$this->_helper->requireUser()->isValid() ) return;
        $viewer = Engine_Api::_()->user()->getViewer();
        $flashgame = Engine_Api::_()->getItem('flashgame', $this->_getParam('flashgame_id'));
        $table = $flashgame->getTable();
        $db = $table->getAdapter();
        $db->beginTransaction();

        try
        {
            $flashgame->closed = $this->_getParam('closed');
            $flashgame->save();

            $db->commit();
        }

        catch( Exception $e )
        {
            $db->rollBack();
            throw $e;
        }
        return $this->_redirect("admin/games/manage/index/page/".$this->_getParam('page',1));
    }


    // Utility
    public function getNavigation($active = false)
    {
        if( is_null($this->_navigation) )
        {
            $navigation = $this->_navigation = new Zend_Navigation();

            if( Engine_Api::_()->user()->getViewer()->getIdentity() )
            {
                $navigation->addPage(array(
                'label' => Zend_Registry::get('Zend_Translate')->_('Browse Games'),
                'route' => 'flashgame_browse',
                'module' => 'flashgame',
                'controller' => 'index',
                'action' => 'index'
                ));
                /*
                $navigation->addPage(array(
                'label' => Zend_Registry::get('Zend_Translate')->_('User\'s Ratings'),
                'route' => 'flashgame_index_userratings',
                'module' => 'flashgame',
                'controller' => 'index',
                'action' => 'userratings'
                ));
                */
                $navigation->addPage(array(
                'label' => Zend_Registry::get('Zend_Translate')->_('My Games'),
                'route' => 'flashgame_manage',
                'module' => 'flashgame',
                'controller' => 'index',
                'action' => 'manage',
                'active' => $active
                ));
                if( $this->_helper->requireAuth()->setAuthParams('flashgame', null, 'create')->checkRequire()){
                    $navigation->addPage(array(
                    'label' => Zend_Registry::get('Zend_Translate')->_('Post a New Game'),
                    'route' => 'flashgame_create',
                    'module' => 'flashgame',
                    'controller' => 'index',
                    'action' => 'create'
                    ));
                }
                $navigation->addPage(array(
                'label' => Zend_Registry::get('Zend_Translate')->_('My Packages'),
                'route' => 'flashgame_userpackages',
                'module' => 'flashgame',
                'controller' => 'package',
                'action' => 'userpackages'
                ));
            }
        }
        return $this->_navigation;
    }


    public function handleArchiveList($results)
    {
        $flashgame_dates = array();
        foreach ($results as $result)
            $flashgame_dates[] = strtotime($result->creation_date);

        // GEN ARCHIVE LIST
        $time = time();
        $archive_list = array();

        foreach( $flashgame_dates as $flashgame_date )
        {
            $ltime = localtime($flashgame_date, TRUE);
            $ltime["tm_mon"] = $ltime["tm_mon"] + 1;
            $ltime["tm_year"] = $ltime["tm_year"] + 1900;

            // LESS THAN A YEAR AGO - MONTHS
            if( $flashgame_date+31536000>$time )
            {
                $date_start = mktime(0, 0, 0, $ltime["tm_mon"], 1, $ltime["tm_year"]);
                $date_end = mktime(0, 0, 0, $ltime["tm_mon"]+1, 1, $ltime["tm_year"]);
                $label = date('F Y', $flashgame_date);
                $type = 'month';
            }

            // MORE THAN A YEAR AGO - YEARS
            else
            {
                $date_start = mktime(0, 0, 0, 1, 1, $ltime["tm_year"]);
                $date_end = mktime(0, 0, 0, 1, 1, $ltime["tm_year"]+1);
                $label = date('Y', $flashgame_date);
                $type = 'year';
            }

            if( !isset($archive_list[$date_start]) )
            {
                $archive_list[$date_start] = array(
                'type' => $type,
                'label' => $label,
                'date_start' => $date_start,
                'date_end' => $date_end,
                'count' => 1
                );
            }
            else
            {
                $archive_list[$date_start]['count']++;
            }
        }

        //krsort($archive_list);
        return $archive_list;
    }
}